package net.yebaihe.wc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import net.yebaihe.wc.Dishes.AssetToSDRunnable;
import net.yebaihe.wc.Dishes.DishSimpleCursorAdapter;
import net.yebaihe.wc.NearBy.RestaurantSimpleCursorAdapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class Favorites extends StateMachine{

	private SQLiteDatabase listdb;
	private ListView lstFavoriteDishes;
	private ListView lstFavoriteRestaurant;

	@Override
	protected String getTopbarTitle() {
		return "收藏";
	}
	
	private OnItemClickListener changetodish=new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,
				int arg2, long id) {
			getWCAppContext().restaurant=id;
			changeToActivity(Dishes.class);
		}
	};
	private OnItemLongClickListener delFavoriteR=new OnItemLongClickListener(){
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			Cursor c=listdb.rawQuery("select * from restaurants where _id="+arg3, null);
			c.moveToFirst();
			final long rid=arg3;
			new AlertDialog.Builder(Favorites.this).setTitle(R.string.app_name)
				.setNegativeButton("取消", null)
				.setMessage("确定要删除您收藏的餐厅 "+c.getString(1)+" 吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						UserInfoData userinfo = MyHelper.get(Favorites.this).getCurrUserInfoData(getWCAppContext().email);
						SQLiteDatabase db = MyHelper.get(Favorites.this).getWritableDatabase();
						db.delete("favoriter", "restaurant="+rid+" and uid="+userinfo._id, null);
						db.close();
						refreshLstFavoriteR();
					}
				}).create().show();
			c.close();
			return false;
		}
	};

	class RestaurantSimpleCursorAdapter extends SimpleCursorAdapter{

		public RestaurantSimpleCursorAdapter(Context nearBy, int itemnearby,
				Cursor c, String[] strings, int[] is) {
			super(nearBy,itemnearby,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			/*if (cursor.getPosition() % 2==0){
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				view.setBackgroundResource(R.drawable.rest_bg_2);
			}*/
			TextView v=(TextView) view.findViewById(R.id.txtstyle);
			Cursor c=listdb.rawQuery("select * from style where _id in (select style from style_restaurant where restaurant="+cursor.getLong(0)+")", null);
			String txt="";
			while (c.moveToNext()){
				if (txt.length()<=0){
					txt+=c.getString(1);
				}
				else{
					txt+=","+c.getString(1);
				}
			}
			c.close();
			v.setText(txt);
			
		}
		
	}

	
	class AssetToSDRunnable implements Runnable{

		private int id;

		public AssetToSDRunnable(int id) {
			this.id=id;
		}

		@Override
		public void run() {
			AssetManager am = Favorites.this.getAssets();
			try {
				InputStream is = am.open(id+".dat");
				String path=getLocalDishPath(id);
				File fd=new File(path);
				if (!fd.exists()){
					FileOutputStream os = new FileOutputStream(path);
					byte[] buf = new byte[1024];
					int n = 0;
					int o = 0;
					while ((n = is.read(buf, o, buf.length)) != -1) {
						os.write(buf, 0, n);
					}
					is.close();
					os.close();
				}

				File ft=new File(path+".thumb");
				if (!ft.exists()){
					Bitmap thumb=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), 50, 50, true);
					try {
						FileOutputStream out = new FileOutputStream(path+".thumb");
						thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					refreshLstFavorites();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	
	class DishSimpleCursorAdapter extends SimpleCursorAdapter{

		public DishSimpleCursorAdapter(Favorites dishes, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(dishes,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);

			/*if (cursor.getPosition() % 2==0){
				//view.setBackgroundColor(R.drawable);
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				//view.setBackgroundColor(0xFFdde4f6);
				view.setBackgroundResource(R.drawable.rest_bg_2);

			}*/

			TextView tst=(TextView)view.findViewById(R.id.txttimeinsession);
			tst.setText("");

			
			TextView ts=(TextView)view.findViewById(R.id.txtorders);
			Cursor c=listdb.rawQuery("select * from restaurants where _id="+cursor.getLong(1), null);
			if (c.moveToFirst()){
				ts.setText(c.getString(1));
			}
			c.close();
			
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			img.setTag(getLocalDishPath(cursor.getInt(0)));
			img.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Log.d("", arg0.getTag().toString());
					showBigImage(arg0.getTag().toString());
				}
			});
			File f=new File(getLocalDishPath(cursor.getInt(0))+".thumb");
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}
			else{
				//从网址获取图片
				//File f1=new File(getLocalDishPath(cursor.getInt(0)));
				//if (!f1.exists())
				//	new HttpConnection(Dishes.this, dishImgHandler).file(cursor.getString(7), getLocalDishPath(cursor.getInt(0)));
				
				//Offline version get image from assets
				new Handler().postDelayed(new AssetToSDRunnable(cursor.getInt(0)), 100);
			}
		}
	}
	
	public String getLocalDishPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/dishes/"+getWCAppContext().restaurant+"/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}

	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		View btnFavoriteDish=LayoutInflater.from(this).inflate(R.layout.btnfavoritedish, null);
		View btnFavoriteRestaurant=LayoutInflater.from(this).inflate(R.layout.btnfavoriterestaurant, null);

		LinearLayout tab2=(LinearLayout)this.findViewById(R.id.tab2);
        LinearLayout layoutFavoriteDish = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutfavoritedishes, null);
		lstFavoriteDishes=(ListView) layoutFavoriteDish.findViewById(R.id.lstfavorites);
        tab2.addView(layoutFavoriteDish,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));      

        LinearLayout tab1=(LinearLayout)this.findViewById(R.id.tab1);
        LinearLayout layoutFavoriteRestaunt = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutfavoriterestaurant, null);
        lstFavoriteRestaurant=(ListView) layoutFavoriteRestaunt.findViewById(R.id.lstfavorites);
        tab1.addView(layoutFavoriteRestaunt,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));        
        
        lstFavoriteRestaurant.setOnItemClickListener(changetodish);
        lstFavoriteRestaurant.setOnItemLongClickListener(delFavoriteR);
        
        final TabHost tabHost;
        tabHost=(TabHost) client.findViewById(R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("restaurant").setContent(R.id.tab1).setIndicator(btnFavoriteRestaurant));
        tabHost.addTab(tabHost.newTabSpec("dishes").setContent(R.id.tab2).setIndicator(btnFavoriteDish));
        tabHost.setOnTabChangedListener(new OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("dishes")){
					refreshLstFavorites();
				}
				else if (tabId.equals("restaurant")){
					refreshLstFavoriteR();
				}
			}
        });
        refreshLstFavoriteR();
        tabHost.setCurrentTab(0);
	}

	private void refreshLstFavoriteR() {
		if (listdb!=null){
			UserInfoData userinfo = MyHelper.get(Favorites.this).getCurrUserInfoData(getWCAppContext().email);
			String sql="select _id,name,('人均' || avgprice || '元') as avgprice,discountdesc,style,(round(length,2) || '公里') as length from restaurants where _id in (select restaurant from favoriter where uid="+
					userinfo._id+")";
			refreshRestaurantListView(lstFavoriteRestaurant,sql);		
		}
	}

	private void refreshRestaurantListView(ListView lv,
			String sql) {
		if (listdb!=null){
			Cursor c=listdb.rawQuery(sql, null);
			startManagingCursor(c);
			ListAdapter listAdapter = new RestaurantSimpleCursorAdapter(this, R.layout.itemnearby,
					c,
					new String[]{"name","avgprice","discountdesc","style","length"},
					new int[]{R.id.txtname,R.id.txtavgprice,R.id.txtdiscount,R.id.txtstyle,R.id.txtlength});
			lv.setAdapter(listAdapter);
		}
	}

	private void refreshLstFavorites() {
		if (listdb!=null){
			UserInfoData userinfo = MyHelper.get(Favorites.this).getCurrUserInfoData(getWCAppContext().email);
			Cursor c=listdb.rawQuery("select *,price || '元' as price,'被点过 '||ordertimes||' 次' as ordertimes from dishes where _id in(select dishid from favorites where uid="+userinfo._id+")", null);
			//Toast.makeText(this, "total:"+c.getCount(), Toast.LENGTH_SHORT).show();
			startManagingCursor(c);
			ListAdapter listAdapter = new DishSimpleCursorAdapter(this, R.layout.itemdish,
					c,
					new String[]{"name","price"},
					new int[]{R.id.txtname,R.id.txtprice});
			lstFavoriteDishes.setAdapter(listAdapter);
			
			lstFavoriteDishes.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					Cursor d=listdb.rawQuery("select * from dishes where _id="+arg3, null);
					d.moveToFirst();
					
					Cursor r=listdb.rawQuery("select * from restaurants where _id="+d.getLong(1), null);
					r.moveToFirst();
					
					final long restaurantid=d.getLong(1);
					final long dishid=arg3;
					
					new AlertDialog.Builder(Favorites.this).setTitle(R.string.app_name)
					.setMessage("您要转到 "+r.getString(1)+" 并且点一份 "+d.getString(2)+" 吗？")
					.setPositiveButton("确定",new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							getWCAppContext().pendingOrder=dishid;
							getWCAppContext().restaurant=restaurantid;
							changeToActivity(Dishes.class);
						}
					}).create().show();
					
					d.close();
					r.close();
				}
			});
			
			lstFavoriteDishes.setOnItemLongClickListener(new OnItemLongClickListener(){
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final long dishid=arg3;
					Cursor c=listdb.rawQuery("select * from dishes where _id="+arg3, null);
					c.moveToFirst();
					new AlertDialog.Builder(Favorites.this).setTitle("收藏")
						.setMessage("您确实要从收藏列表中删除 "+c.getString(2)+" 吗？")
						.setPositiveButton("是的", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								UserInfoData userinfo = MyHelper.get(Favorites.this).getCurrUserInfoData(getWCAppContext().email);
								SQLiteDatabase db = MyHelper.get(Favorites.this).getWritableDatabase();
								db.delete("favorites", "dishid="+dishid+" and uid="+userinfo._id, null);
								db.close();
								refreshLstFavorites();
							}
						})
						.setNegativeButton("取消", null).create().show();
					c.close();
					return true;
				}
			});
		}
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.favorites;
	}
	@Override
	public void onDestroy(){
		listdb.close();
		super.onDestroy();
	}

}
